import {Button, Card, Col, DatePicker, Empty, Flex, Form, FormProps, Image, Progress, Row, Select, Spin, Typography} from "antd";
import {useState} from "react";
import useApp from "antd/es/app/useApp";
import {getRecommend, getRecommendImage} from "./utils/http.ts";
import {Dayjs} from "dayjs";

const {Title, Text} = Typography;


const RecommendPage = ({cities, setCurrentCity}: any) => {
    const [loading, setLoading] = useState<boolean>(false);
    const [result, setResult] = useState<RecommendResult | null>(null);
    const [images, setImages] = useState<string[]>([]);
    const {message} = useApp();

    type FieldType = {
        cityName?: string;
        targetDate?: Dayjs;
        age?: string;
        gender?: string;
    };

    const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
        console.log(values);
        if (!values.cityName || !values.targetDate || !values.age || !values.gender) {
            message.warning('请完善表单');
            return;
        }
        setLoading(true);
        setResult(null);
        setImages([]);

        try {
            const res: any = await getRecommend(values.cityName, values.age, values.gender, values.targetDate.format("YYYY-MM-DD"));
            if (res) {
                setResult(res);
                await fetchImages({
                    "prompt": res.prompt,
                    "n": 2
                });
            } else {
                message.error('推荐失败');
            }
        } catch (error) {
            message.error('服务器异常');
        } finally {
            setLoading(false);
        }
    };

    const fetchImages = async (r: any) => {
        try {
            const res: any = await getRecommendImage(r);
            if (res.status === 'success') {
                setImages(res.data.images);
            }
        } catch (error) {
            console.error('图片加载失败', error);
        }
    };

    type Attribute = {
        attr: string;
        value: number;
    };

    type RecommendResult = {
        recommended_attributes: Attribute[];
        city_info: { city_name: string };
        target_date: string;
        prompt: string;
    };

    const ageOptions = [
        {
            label: "age <= 17",
            value: "0-17"
        },
        {
            label: "18 <= age <= 25",
            value: "18-25"
        },
        {
            label: "25 <= age <= 40",
            value: "25-40"
        },
        {
            label: "age >= 41",
            value: "41-NA"
        },
    ]

    const genderOptions = [
        {
            label: "男",
            value: "genderM"
        },
        {
            label: "女",
            value: "genderF"
        },
    ]

    return (
        <Flex style={{flexDirection: 'column', margin: "10px", overflow: "hidden"}} gap={"middle"}>
            <Card>
                <Title level={3} style={{textAlign: 'center'}}>推荐参数设置</Title>
                <Form
                    layout="vertical"
                    onFinish={onFinish}
                    style={{maxWidth: 600, margin: '0 auto'}}
                >
                    <Form.Item<FieldType> label="选择城市" name="cityName"
                                          rules={[{required: true, message: '请选择城市'}]}>
                        <Select options={cities} onSelect={(value: string) => {
                            setCurrentCity(value);
                        }} placeholder="请选择城市"/>
                    </Form.Item>

                    <Form.Item<FieldType> label="选择年龄" name="age"
                                          rules={[{required: true, message: '请选择年龄'}]}>
                        <Select options={ageOptions} onSelect={(value: string) => {
                            setCurrentCity(value);
                        }} placeholder="请选择年龄"/>
                    </Form.Item>
                    <Form.Item<FieldType> label="选择性别" name="gender"
                                          rules={[{required: true, message: '请选择性别'}]}>
                        <Select options={genderOptions} onSelect={(value: string) => {
                            setCurrentCity(value);
                        }} placeholder="请选择性别"/>
                    </Form.Item>

                    <Form.Item<FieldType> label="目标日期" name="targetDate"
                                          rules={[{required: true, message: '请选择日期'}]}>
                        <DatePicker style={{width: '100%'}} placeholder={"请选择日期"}/>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" block loading={loading}>
                            生成智能推荐
                        </Button>
                    </Form.Item>
                </Form>
            </Card>

            {/* 推荐结果 */}
            {result && (
                <Card>
                    <Title level={4}>推荐属性分析</Title>
                    <Row gutter={[16, 16]}>
                        {result.recommended_attributes.map((attr, idx) => (
                            <Col xs={24} sm={12} md={8} lg={6} key={idx}>
                                <Card hoverable style={{borderRadius: 12}}>
                                    <Text strong>{attr.attr!}</Text>
                                    <Progress
                                        percent={parseFloat((attr.value * 100).toFixed(1))}
                                        showInfo={false}
                                        size="small"
                                        strokeColor="#4a90e2"
                                        style={{marginTop: 12}}
                                    />
                                    <div style={{
                                        marginTop: 8,
                                        color: '#999'
                                    }}>置信度：{(attr.value * 100).toFixed(1)}%
                                    </div>
                                </Card>
                            </Col>
                        ))}
                    </Row>
                </Card>
            )}

            {/* 图片展示 */}
            {loading && (
                <Flex justify="center" style={{margin: '50px 0'}}>
                    <Spin size="large"/>
                </Flex>
            )}

            {images.length > 0 && (
                <Card>
                    <Title level={4}>搭配效果展示</Title>
                    <Row gutter={[16, 16]}>
                        {images.map((imgUrl, idx) => (
                            <Col xs={24} sm={12} md={8} lg={6} key={idx}>
                                <Card
                                    cover={<Image alt={`搭配${idx + 1}`} src={imgUrl}
                                                  style={{height: 300, objectFit: 'cover'}}/>}
                                    hoverable
                                    style={{borderRadius: 12}}
                                >
                                    <Text type="secondary" style={{fontSize: 12}}>AI生成搭配方案</Text>
                                </Card>
                            </Col>
                        ))}
                    </Row>
                </Card>
            )}

            {!loading && result && images.length === 0 && (
                <Empty description="暂无搭配图片，稍后再试"/>
            )}
        </Flex>
    );
};

export default RecommendPage;
